//
//  shangpinlistViewController.m
//  BAOASystem
//
//  Created by michael on 2018/3/9.
//  Copyright © 2018年 czd. All rights reserved.
//
#import "PTLMaskingView.h"
#import "OALoginViewController.h"
#import "fajianxqViewController.h"
#import "qiyecaigouxqCollectionViewCell.h"
#import "MJRefresh.h"
#import "shangpinlistViewController.h"
#import "productbiglistCollectionViewCell.h"
#import "productmidlistCollectionViewCell.h"
@interface shangpinlistViewController ()

@end

@implementation shangpinlistViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    


            [self loadData]; //加载网络数据
self.view.backgroundColor = [UIColor whiteColor];
      UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
           layout.itemSize = CGSizeMake(KScreenWidth, 200);
;

          layout.scrollDirection = UICollectionViewScrollDirectionVertical;

     layout.minimumLineSpacing = 1; //设置行间距
layout.minimumInteritemSpacing = 1; //设置列间距
   self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 30, KScreenWidth, KScreenHeight-kTopHeight-30) collectionViewLayout:layout];
//if (@available(iOS 11.0, *)) {
//                    _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//                }else {
//                    self.automaticallyAdjustsScrollViewInsets = NO;
//                }
self.collectionView.alwaysBounceVertical = YES;
      self.collectionView.dataSource = self;
        self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor colorWithHexString:@"f0eff5"];
        self.collectionView.backgroundColor = [UIColor whiteColor];

//        self.collectionView.showsVerticalScrollIndicator = NO;
//        self.collectionView.showsHorizontalScrollIndicator = NO;
               [ self.collectionView registerClass:[productbiglistCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([productbiglistCollectionViewCell class])];
        [ self.collectionView registerClass:[productmidlistCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([productmidlistCollectionViewCell class])];
    

    //self.collectionView.myDelegate = self;
    [self.view addSubview:self.collectionView];
     [MBProgressHUD showHUDAddedTo:self.view animated:YES];

     __weak typeof(self) weakSelf = self;
    [self.collectionView addHeaderWithCallback:^{
            weakSelf.currentPage = 1;
        [weakSelf loadData]; //加载网络数据
    }];
    [self.collectionView headerBeginRefreshing];

    [self.collectionView addFooterWithCallback:^{
          if (weakSelf.lastPage==0 ){
     [weakSelf loadMore];
        }else{

            [weakSelf.collectionView footerEndRefreshing];
            [weakSelf.view makeToast:NSLocalizedString(@"没有更多了", nil)];
        }

    }];
//            [weakSelf.collectionView footerEndRefreshing];
         self.navigationItem.titleView = self.searchBar;

    // Do any additional setup after loading the view.
}
#pragma mark: getter method EVNCustomSearchBar
- (EVNCustomSearchBar *)searchBar
{
    if (!_searchBar)
    {
        _searchBar = [[EVNCustomSearchBar alloc] initWithFrame:CGRectMake(0, kStatusBarHeight, KScreenWidth, 30)];
//0a62ea
        _searchBar.backgroundColor = [UIColor clearColor]; // 清空searchBar的背景色
                _searchBar.textFieldColor = [UIColor colorWithHexString:@"fbf2f2"alpha:.32];
                _searchBar.textColor = [UIColor whiteColor];
    [_searchBar.cancelButton setTitleColor:[UIColor whiteColor]forState:UIControlStateNormal];
//        _searchBar.iconImage = [UIImage imageNamed:@"EVNCustomSearchBar.bundle/searchImageBlue.png"];
    _searchBar.iconImage = [UIImage imageNamed:@"search"];

        _searchBar.iconAlign = EVNCustomSearchBarIconAlignCenter;
        [_searchBar setPlaceholder:NSLocalizedString(@"请输入关键字", nil)];  // 搜索框的占位符
        _searchBar.placeholderColor = [UIColor whiteColor];
        _searchBar.delegate = self; // 设置代理
        [_searchBar.textField.layer setMasksToBounds:YES];

[_searchBar.textField.layer setCornerRadius:15];//设置矩形四个圆角半径

        [_searchBar sizeToFit];
    }
    return _searchBar;
}
- (void)searchBarTextDidEndEditing:(EVNCustomSearchBar *)searchBar{
if (searchBar.text.length>0){
_searchstring  = _searchBar.text;
[self loadData];}
}
- (void)loadData{
 [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    NSMutableDictionary *dics=[NSMutableDictionary dictionary];
      dics[@"userName"] = @"administrator";
    dics[@"password"] = @"b628e2c3b78ef9bf269c489b35176e48";
    
    dics[@"language"] = [[NSUserDefaults standardUserDefaults] objectForKey:@"language"];
     dics[@"website"] = [[NSUserDefaults standardUserDefaults] objectForKey:@"website"];
        dics[@"type"] = BAtype;
     [dics setValue:_ctgid forKey:@"ctgid"];
          [dics setValue:_areaid forKey:@"areaid"];

   [dics setValue:_searchstring forKey:@"pdname"];
    
  dics[@"pageNumber"] = @"1";
  dics[@"pageSize"] = @"20";


   self.currentPage = 1;

  NSString *dicstring = [httpTool dictionaryToJson:dics];
dicstring= [dicstring URLEncodedString];
NSString *url = [[NSString alloc]initWithFormat:@"%@/api/product/list?data=%@",BAip,dicstring];
 [httpTool ZBPostNetDataWith:url withDic:nil andSuccess:^(NSDictionary* dictionary){
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
             _dic = dictionary;

[self initview];

  if (self.currentPage ==1)
        {
            [self.dataArray removeAllObjects];
        }
  NSLog(@"%@",dictionary);
_dic = dictionary;
  _dataArray = [NSMutableArray array];
  NSDictionary *dic = dictionary[@"productpage"];
    _lastPage = [dic[@"lastPage"]intValue];
  self.totalCounts =[dic[@"totalRow"] intValue];

   NSArray *array = dic[@"list"];
  if (_lastPage!=0 ){
             self.collectionView.footerHidden = YES;
}else{
             self.collectionView.footerHidden = NO;

}
   if (array.count==0) {
                [self.view makeToast:NSLocalizedString(@"没有数据", nil)];

}
for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
[_collectionView reloadData];
        self.currentPage++;

        [self.collectionView headerEndRefreshing];
//                [self.collectionView footerEndRefreshing];

 }andFailure:^{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

         [self.collectionView headerEndRefreshing];


 }];

}
- (void)initview{
if (_btn) {
[_btn removeFromSuperview];
}
    NSArray *array1 = _dic[@"ctglist"];
    NSArray *array2 = _dic[@"arealist"];
    NSMutableArray *listarray1 = [NSMutableArray array];
     NSDictionary *selCtg =_dic[@"selCtg"];
    if ([selCtg count ]!=0) {
        [listarray1 addObject:[NSString stringWithFormat:@"%@%@",NSLocalizedString(@"当前选择", nil),selCtg[@"ctgName"]]];

}
//    [listarray1 addObject:NSLocalizedString(@"清空搜索条件", nil)];

    for (NSDictionary *dic in array1) {
    [listarray1 addObject:dic[@"ctgName"]];
}
  NSMutableArray *listarray2 = [NSMutableArray array];
   NSDictionary *selArea =_dic[@"selArea"];
    if ([selArea count ]!=0) {
        [listarray2 addObject:[NSString stringWithFormat:@"%@%@",NSLocalizedString(@"当前选择", nil),selArea[@"areaname"]]];

}
//  [listarray2 addObject:NSLocalizedString(@"清空搜索条件", nil)];

    for (NSDictionary *dic in array2) {
    [listarray2 addObject:dic[@"areaname"]];
}

    NSArray * listArr1 = listarray1;
    NSArray * listArr2 = listarray2;
        _btn = [[PTLMenuButton alloc]initWithFrame:CGRectMake(0, 0, (KScreenWidth*2/3), 30) menuTitles:@[NSLocalizedString(@"产品类别", nil),NSLocalizedString(@"所有地区", nil)]];

    _btn.listTitles = @[listArr1, listArr2];
    _btn.delegate = self;
    [self.view addSubview:_btn];
  if (!_button) {
_button = [UIButton buttonWithType:UIButtonTypeCustom];
_button.frame = CGRectMake(_btn.right, 0, KScreenHeight/3, 30);
_button.imageEdgeInsets = UIEdgeInsetsMake(0, -80, 0, 0);

[_button setImage:[UIImage imageNamed:@"列表显示"] forState:UIControlStateNormal];
[_button setImage:[UIImage imageNamed:@"大图显示"] forState:UIControlStateSelected];
[_button addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_button];
  }
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 29, self.view.frame.size.width, 1)];
    view.backgroundColor = [UIColor colorWithHexString:@"f0eff5"];
        [self.view addSubview:view];

     __weak typeof(self) weakSelf = self;

  [self.btn.listView.maskingView setButtonblock :^() {
  NSLog(@"11111");
 _areaid = @"";
    _ctgid = @"";
        [weakSelf loadData];

  }];


}
-(void)action:(UIButton *)btn{
 
    if (btn.isSelected) {
        btn.selected = NO;
       // self.goodsShowType = singleLineShowOneGoods;
        self.showType =singleLineShowOneGoods;
            [self loadData];

    } else {
        btn.selected = YES;
       // self.goodsShowType = signleLineShowDoubleGoods;
        self.showType =signleLineShowDoubleGoods;
            [self loadData];

}
}
-(void)ptl_menuButton:(PTLMenuButton *)menuButton didSelectMenuButtonAtIndex:(NSInteger)index selectMenuButtonTitle:(NSString *)title listRow:(NSInteger)row rowTitle:(NSString *)rowTitle{
    NSLog(@"index: %zd, title:%@, listrow: %zd, rowTitle: %@", index, title, row, rowTitle);
      NSArray *array1 = _dic[@"ctglist"];
    NSArray *array2 = _dic[@"arealist"];
    
    if ([rowTitle isEqualToString:NSLocalizedString(@"清空搜索条件", nil)]){
    _areaid = @"";
    _ctgid = @"";
        [self loadData];

    }else if ([rowTitle containsString:NSLocalizedString(@"当前选择", nil)]){
    return;
    }
    else{
    if([title isEqualToString:NSLocalizedString(@"产品类别", nil)]){
    
    
     for (NSDictionary *dic in array1) {
   if ([dic[@"ctgName"]isEqualToString:rowTitle]) {
    _ctgid = dic[@"id"];
}
   
}
    [self loadData];
    }else{
     for (NSDictionary *dic in array2) {
   if ([dic[@"areaname"]isEqualToString:rowTitle]) {
    _areaid = dic[@"id"];
}
   
}
    [self loadData];
    }
    }
}
- (void)loadMore{

    NSMutableDictionary *dics=[NSMutableDictionary dictionary];
      dics[@"userName"] = @"administrator";
    dics[@"password"] = @"b628e2c3b78ef9bf269c489b35176e48";
    
    dics[@"language"] = [[NSUserDefaults standardUserDefaults] objectForKey:@"language"];
     dics[@"website"] = [[NSUserDefaults standardUserDefaults] objectForKey:@"website"];
        dics[@"type"] = BAtype;
     [dics setValue:_ctgid forKey:@"ctgid"];
   [dics setValue:_searchstring forKey:@"pdname"];
              [dics setValue:_areaid forKey:@"areaId"];

  dics[@"pageNumber"] = [NSString stringWithFormat:@"%d",_currentPage];
  dics[@"pageSize"] = @"20";


   self.currentPage = 1;

  NSString *dicstring = [httpTool dictionaryToJson:dics];
dicstring= [dicstring URLEncodedString];
NSString *url = [[NSString alloc]initWithFormat:@"%@/api/product/list?data=%@",BAip,dicstring];
 [httpTool ZBPostNetDataWith:url withDic:nil andSuccess:^(NSDictionary* dictionary){

  NSLog(@"%@",dictionary);
_dic = dictionary;
  NSDictionary *dic = dictionary[@"productpage"];
    _lastPage = [dic[@"lastPage"]intValue];
  self.totalCounts =[dic[@"totalRow"] intValue];

   NSArray *array = dic[@"list"];

for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
        [self.collectionView footerEndRefreshing];

[_collectionView reloadData];
        self.currentPage++;

 }andFailure:^{
         [self.collectionView footerEndRefreshing];

//         [self.tableView headerEndRefreshing];

 }];

}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.showType == singleLineShowOneGoods) {
        
        productbiglistCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([productbiglistCollectionViewCell class]) forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        cell.dic = self.dataArray[indexPath.row];
            [cell layoutSubviews];
            cell.sendbutton.tag = indexPath.row;
            cell.addbutton.tag = indexPath.row;
[cell.sendbutton addTarget:self action:@selector(action1:) forControlEvents:UIControlEventTouchUpInside];
        return cell;

    }else{
        
        productmidlistCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([productmidlistCollectionViewCell class]) forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        cell.dic = self.dataArray[indexPath.row];
            [cell layoutSubviews];
             cell.sendbutton.tag = indexPath.row;
            cell.addbutton.tag = indexPath.row;
[cell.sendbutton addTarget:self action:@selector(action1:) forControlEvents:UIControlEventTouchUpInside];

        return cell;
        
    }
}
- (void)action1:(UIButton *)button{
   UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];


    if (![[[NSUserDefaults standardUserDefaults]objectForKey:@"autoLogin"]isEqualToString:@"Y"]&&![[DanLi sharedDanLi].stay isEqualToString:@"yes"]) {
      OALoginViewController * loginVC = [storyBoard instantiateViewControllerWithIdentifier:@"LoginVC"];
        UINavigationController * navVC = [[UINavigationController alloc]initWithRootViewController:loginVC];
        loginVC.navigationController.navigationBar.hidden = YES;
                 self.view.window.rootViewController = navVC;

}else{
fajianxqViewController *vc = [[fajianxqViewController alloc]init];
vc.hidesBottomBarWhenPushed = YES;

//@property (strong, nonatomic)  NSString *toMemberCompanyId;
//@property (strong, nonatomic)  NSString *toMemberNameId;
//
//@property (strong, nonatomic)  NSString *productId;

        NSDictionary * dic = self.dataArray[button.tag];

vc.productId = dic[@"id"];
vc.toMemberNameId = dic[@"uid"];

vc.toMemberCompanyId = dic[@"cpid"];
[self.navigationController pushViewController:vc animated:YES];

}
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.showType == singleLineShowOneGoods) {
        
        return CGSizeMake(KScreenWidth, 200);
    } else {
        return CGSizeMake(KScreenWidth/2.0-0.5, 9*20+10+100+10);
    }
    
    
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{

return UIEdgeInsetsMake(64,0,0,0);
}
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
//{
//return 0;
//}
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
//{
//return 0;
//}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
        NSDictionary * dic = self.dataArray[indexPath.row];
shangpinxqViewController *vc = [[shangpinxqViewController alloc]init];
vc.pdid = dic[@"id"];
vc.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:vc animated:YES];

}
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
//    
//    return 0.001f;
//
//}
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
//    
//    return 0.001f;
//}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
